export default {
  // 开启命名空间
  namespaced: true,
  state: () => {
    return {
      // 购物车的数组，用来存储购物车中每个商品的信息对象
      // 每个商品的信息对象，都包含如下 6 个属性：
      // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
      cart: uni.getStorageSync('cart') || [],
      // 收货地址
      address: uni.getStorageSync('address') || {}
    }
  },
  getters: {
    // 是否全选
    isCheckAll: state => state.cart.every(item => item.goods_state),
    // 获取选中的商品的总金额
    totalFee: state => state.cart.filter(item => item.goods_state).reduce((total, v) => total += v.goods_count * v
      .goods_price, 0.00).toFixed(2),
    // 获取选中的商品数量
    totalCheckedCount: state => state.cart.filter(item => item.goods_state).reduce((total, v) => total += v.goods_count,
      0),
    // 获取购物车商品数量(所有的商品)
    totalCount: state => state.cart.reduce((total, v) => total += v.goods_count, 0),
    // 收货详细地址的计算属性
    addstr: state => {
      if (!state.address.provinceName) return ''
      // 拼接 省，市，区，详细地址 的字符串并返回给用户
      return state.address.provinceName + state.address.cityName + state.address.countyName + state.address.detailInfo
    }
  },
  mutations: {
    // 全选和全不选的切换
    updateGoodsState(state, goods_state) {
      state.cart.forEach(item => item.goods_state = goods_state)
      // 持久化存储
      this.commit('cart/saveToStorage')
    },
    // 更新收货地址
    updateAddress(state, address) {
      console.log(address)
      state.address = address
      uni.setStorageSync('address', address)
    },
    addToCart(state, goods) {
      // 两种情况：1.如果该商品在购物车中没有，那么就直接追加到数组中；2.如果该商品在购物车中有，那就进行购物车数量的累加
      const findResult = state.cart.find(v => v.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_count += goods.goods_count
      } else {
        state.cart.push(goods)
      }
      // 持久化存储
      this.commit('cart/saveToStorage')
    },
    // 修改购物车数据
    updateCart(state, goods) {
      const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
      if (findResult) {
        for (const key in findResult) {
          findResult[key] = goods[key]
        }
      }
      // 持久化存储
      this.commit('cart/saveToStorage')
    },
    // 删除购物车数据
    deleteCart(state, goods) {
      state.cart = state.cart.filter(item => item.goods_id !== goods.goods_id)
      // 持久化存储
      this.commit('cart/saveToStorage')
    },
    // 购物车数据的持久化存储
    // 将购物车中的数据持久化存储到本地
    saveToStorage(state) {
      uni.setStorageSync('cart', state.cart)
    }
  },
  actions: {}
}
